import { connectToDb } from "./db";
import { Post, User } from "./models";
import { unstable_noStore } from "next/cache";
connectToDb();

export const getPosts = async () => {
  try {
    const posts = await Post.find();
    return posts;
  } catch (error) {
    throw new Error(error);
  }
};

export const getPost = async (id) => {
  try {
    const post = await Post.findOne({ _id: id });
    return post;
  } catch (error) {
    throw new Error(error);
  }
};

// const getCachedUser = unstable_cache(
//   async (id) => User.findById(id),
//   ["my-app-user"]
// );
export const getUser = async (id) => {
  unstable_noStore();
  try {
    const user = await User.findById(id);
    return user;
  } catch (error) {
    throw new Error(error);
  }
};

export const createUser = async (formData) => {
  try {
    await new User(formData).save();
  } catch (error) {
    throw new Error(error);
  }
};
